﻿using Authority.Model;
using Common.Library;
using Container.Library;
using Dapper.Library;
using Dapper.MsSql.Library;
using Network.Library;
using Project.Model;
using Redis.Library;
using Dapper.Library.DataAccessSql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tool.Model;

namespace Project.Logic
{
    /// <summary>
    /// 工程操作逻辑类
    /// </summary>
    public class ProjectServiceImpl : IProjectService
    {

        /// <summary>
        /// 获取所有的工程项目
        /// </summary>
        /// <param name="parametersInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<ProjectInfoQueryResponse>> LoadProjectAllList()
        {
            var resultInfo = new ResultJsonInfo<List<ProjectInfoQueryResponse>>();
            var loginUser = UserSession.GetLoginUser<SysUserInfo>();
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.ErpDB_MsSql))
            {
                var listInfo = con.QuerySet<T_ProjectEntity>().WithNoLock()
                    .AndWhere(p => p.IsDel == 0 && p.DepNo == loginUser.OrganizationCode)
                    .Multiple();

                if (listInfo.IsNotNull())
                {
                    var projectInfoList = listInfo.ToList().MapToList<ProjectInfoQueryResponse>();
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = projectInfoList;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }


        /// <summary>
        /// 根据条件获取工程基础信息
        /// </summary>
        /// <param name="parametersInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<ProjectInfoQueryResponse>> LoadProjectList(ParametersInfo<ProjectInfoQueryRequest> inputInfo)
        {

            var resultInfo = new ResultJsonInfo<List<ProjectInfoQueryResponse>>();
            var loginUser = UserSession.GetLoginUser<SysUserInfo>();

            using (var con = MsSqlDataBase.GetConnection(DatabaseName.ErpDB_MsSql))
            {
                var result = con.QuerySet<T_ProjectEntity>().WithNoLock()
                    .AndWhere(p => p.IsDel == 0);

                if (inputInfo.parameters.sKeyWords.IsNotNullOrEmpty())
                {
                    result = result.AndWhere(p => p.ProjectName.Contains(inputInfo.parameters.sKeyWords));
                }
                if (inputInfo.parameters.dBeginTime.IsNotNull())
                {
                    result = result.AndWhere(p => p.StartDate >= inputInfo.parameters.dBeginTime);
                }
                if (inputInfo.parameters.dEndTime.IsNotNull())
                {
                    result = result.AndWhere(p => p.EndDate <= inputInfo.parameters.dBeginTime);
                }
                result.AndWhere(p => p.DepNo == loginUser.OrganizationCode);

                var listInfo = result.OrderBy(inputInfo.order == "asc" ? OrderByType.Asc : OrderByType.Desc, inputInfo.field)
                    .PageList(inputInfo.page, inputInfo.limit);

                if (listInfo.Data.IsNotNull())
                {
                    var projectInfoList = listInfo.Data.ToList().MapToList<ProjectInfoQueryResponse>();
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = projectInfoList;
                    resultInfo.Count = listInfo.Total;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        #region 保存信息

        //共享锁
        private static object NumberLock = new object();
        /// <summary>
        /// 保存信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Save(ProjectOperateRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<int>();
            var loginUser = UserSession.GetLoginUser<SysUserInfo>();
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.ErpDB_MsSql))
            {
                var result = 0;

                var projectInfo = inputInfo.MapTo<T_ProjectEntity>();

                if (inputInfo.ID > 0)
                {
                    #region UpdateByExp T_ProjectEntity
                    //result = con.CommandSet<T_ProjectEntity>()
                    //    .IfNotExists(p => p.ID != inputInfo.ID && (p.ProjectName == projectInfo.ProjectName))
                    //    .UpdateByExp(p => new T_ProjectEntity
                    //     {
                    //         ProjectName = projectInfo.ProjectName,
                    //         ProjectTypeID = projectInfo.ProjectTypeID,
                    //         StartDate = projectInfo.StartDate,
                    //         EndDate = projectInfo.EndDate,
                    //         Contract = projectInfo.Contract,
                    //         Charge = projectInfo.Charge,
                    //         Phone = projectInfo.Phone,
                    //         ProjectArea = projectInfo.ProjectArea,
                    //         ContractMoney = projectInfo.ContractMoney,
                    //         ChinaMoney = NumeralHelper.MoneyToUpper(projectInfo.ContractMoney.ToString()),
                    //         AuditMoney = projectInfo.AuditMoney,
                    //         AuditChinaMoney = NumeralHelper.MoneyToUpper(projectInfo.AuditChinaMoney.ToString()),
                    //         SJDW = projectInfo.SJDW,
                    //         JSDW = projectInfo.JSDW,
                    //         SGDW = projectInfo.SGDW,
                    //         Descrption = projectInfo.Descrption
                    //     });
                    #endregion

                    projectInfo.AuditChinaMoney = NumeralHelper.MoneyToUpper(projectInfo.AuditMoney.ToString());
                    projectInfo.ChinaMoney = NumeralHelper.MoneyToUpper(projectInfo.ContractMoney.ToString());
                    projectInfo.ProjectType=  EnumExtentions.GetEnumStringByValue(int.Parse(projectInfo.ProjectTypeID.ToString()), typeof(ProjectType));

                    result = con.CommandSql<int>().BySql(DataCommandManager.GetSQLCommand("UpdateProjectByExp", "Project"),
                        new
                        {
                            ID= projectInfo.ID,
                            ProjectName = projectInfo.ProjectName,
                            ProjectTypeID = projectInfo.ProjectTypeID,
                            ProjectType = projectInfo.ProjectType,
                            StartDate = projectInfo.StartDate,
                            EndDate = projectInfo.EndDate,
                            Contract = projectInfo.Contract,
                            Charge = projectInfo.Charge,
                            Phone = projectInfo.Phone,
                            ProjectArea = projectInfo.ProjectArea,
                            ContractMoney = projectInfo.ContractMoney,
                            ChinaMoney = projectInfo.ChinaMoney,
                            AuditMoney = projectInfo.AuditMoney,
                            AuditChinaMoney = projectInfo.AuditChinaMoney,
                            SJDW = projectInfo.SJDW,
                            JSDW = projectInfo.JSDW,
                            SGDW = projectInfo.SGDW,
                            Descrption = projectInfo.Descrption
                        }).ExecuteNoQuery();
                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "操作成功！";
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败,项目名称重复！";
                    }
                }
                else
                {
                    projectInfo.AuditChinaMoney = NumeralHelper.MoneyToUpper(projectInfo.AuditMoney.ToString());
                    projectInfo.ChinaMoney = NumeralHelper.MoneyToUpper(projectInfo.ContractMoney.ToString());
                    projectInfo.DepNo = loginUser.OrganizationCode;
                    projectInfo.ProjectNo = GetNumber().ToString();
                    projectInfo.CreateTime = DateTime.Now;
                    projectInfo.CreateUserNo = loginUser.Code;
                    projectInfo.ProjectType = EnumExtentions.GetEnumStringByValue(int.Parse(projectInfo.ProjectTypeID.ToString()), typeof(ProjectType));
                    projectInfo.IsDel = 0;
                    projectInfo.CheckZT = 0;
                    result = con.CommandSql<int>().BySql(DataCommandManager.GetSQLCommand("AddProject", "Project"),
                        new
                        {
                            ProjectName = projectInfo.ProjectName,
                            DepNo = loginUser.OrganizationCode,
                            ProjectNo = projectInfo.ProjectNo,
                            CreateTime = projectInfo.CreateTime,
                            CreateUserNo = projectInfo.CreateUserNo,
                            ProjectTypeID = projectInfo.ProjectTypeID,
                            ProjectType=projectInfo.ProjectType,
                            StartDate = projectInfo.StartDate,
                            EndDate = projectInfo.EndDate,
                            Contract = projectInfo.Contract,
                            Charge = projectInfo.Charge,
                            Phone = projectInfo.Phone,
                            ProjectArea = projectInfo.ProjectArea,
                            ContractMoney = projectInfo.ContractMoney,
                            ChinaMoney = projectInfo.ChinaMoney,
                            AuditMoney = projectInfo.AuditMoney,
                            AuditChinaMoney = projectInfo.AuditChinaMoney,
                            SJDW = projectInfo.SJDW,
                            JSDW = projectInfo.JSDW,
                            SGDW = projectInfo.SGDW,
                            Descrption = projectInfo.Descrption,
                            CheckZT = projectInfo.CheckZT,
                            IsDel= projectInfo.IsDel
                        }).ExecuteNoQuery();

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "操作成功！";
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败,项目名称重复！";
                    }
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 获取组织机构编码
        /// </summary>
        /// <returns></returns>
        public static long GetNumber()
        {
            StringBuilder sb = new StringBuilder();
            lock (NumberLock)
            {
                string newBase = DateTime.Now.ToString("yyMMddHHmmssfff");

                string noIndex = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                    .StringGet(ConstRedisKey.RedisProjectCode);

                if (noIndex.IsNullOrEmpty() || noIndex == "null")
                {
                    int index = NumeralHelper.Next(90) + 10;
                    RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                        .StringSet(ConstRedisKey.RedisProjectCode, index.ToString());
                    sb.Append(newBase + index);
                }
                else
                {
                    if (int.Parse(noIndex) < 99)
                    {
                        var index = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb).SetStringIncrement(ConstRedisKey.RedisProjectCode);
                        sb.Append(newBase + index);
                    }
                    else
                    {
                        var index = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb).StringSet(ConstRedisKey.RedisProjectCode, "10");
                        sb.Append(newBase + 10);
                    }
                }
            }
            return long.Parse(sb.ToString());
        }

        #endregion

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<int> IdList)
        {

            var resultInfo = new ResultJsonInfo<int>();
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.ErpDB_MsSql))
            {
                var result = 0;
                if (IdList.Count >= 0)
                {
                    result = con.CommandSql<int>().BySql(DataCommandManager.GetSQLCommand("BatchRemoveProjects", "Project"),
                         new
                         {
                             Ids = IdList
                         }).ExecuteNoQuery();

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "操作成功！";
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
                else
                {
                    resultInfo.Msg = "ID为空，操作失败！";
                }
            }
            return resultInfo;
        }

    }
}
